<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>节流和防抖</title>
  <button class="throttle">点我使用节流发送请求</button>
  <button class="debounce">点我使用防抖发送请求</button>
</head>

<body>
  <script>
    const fetchData = (id) => {
      console.log('当前接收到的参数', id)
      fetch('https://dog.ceo/api/breeds/image/random').then(res => res.json()).then(data => {
        console.log(data)
      })
    }

    const throttle = (fn, delay) => {
      let timeId = null
      return function (...args) {
        if (timeId) return // 如果已经有一个定时器在运行，直接返回  
        timeId = setTimeout(() => {
          fn.apply(this, args) // 延迟 delay 毫秒后执行函数  
          timeId = null // 函数执行完毕后清除 timerId，以便下次可以重新设置定时器  
        }, delay)
      }
    }
    const debounce = (fn, delay) => {
      let timeId = null
      return function (...args) {
        if (timeId) clearTimeout(timeId)
        timeId = setTimeout(() => {
          fn.apply(this, args)
          timeId = null
        }, delay)
      }
    }

    let i = 0


    const debounceBtn = document.querySelector('.debounce')
    const throttleBtn = document.querySelector('.throttle')

    const myThrottle = throttle(fetchData, 1000)
    throttleBtn.addEventListener('click', function () {
      myThrottle(i++)
    })

    const myDebounce = debounce(fetchData, 1000)
    debounceBtn.addEventListener('click', () => { myDebounce(i++) })



  </script>
</body>

</html>